package com.utils.network.factory;

import androidx.lifecycle.LiveData;

import com.utils.network.api.ApiConfig;
import com.utils.network.api.ApiResponse;

import org.jetbrains.annotations.NotNull;

import java.lang.reflect.Type;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicBoolean;

import retrofit2.Call;
import retrofit2.CallAdapter;
import retrofit2.Callback;
import retrofit2.Response;

public class LiveDataCallAdapter<T> implements CallAdapter<ApiResponse<T>, LiveData<ApiResponse<T>>> {
    private Type responseType;

    public LiveDataCallAdapter(Type responseType) {
        this.responseType = responseType;
    }

    @NotNull
    @Override
    public Type responseType() {
        return responseType;
    }

    @NotNull
    @Override
    public LiveData<ApiResponse<T>> adapt(@NotNull final Call<ApiResponse<T>> call) {
        LiveData<ApiResponse<T>> liveData = new LiveData<ApiResponse<T>>() {
            private AtomicBoolean started = new AtomicBoolean(false);

            @Override
            protected void onActive() {
                super.onActive();
                if (started.compareAndSet(false, true)) {//确保执行一次
                    call.enqueue(new Callback<ApiResponse<T>>() {
                        @Override
                        public void onResponse(@NotNull Call<ApiResponse<T>> call, @NotNull Response<ApiResponse<T>> response) {
                            if (response.body() != null) {
                                response.body().setOk(response.body().getCode() == 0);
                            }
                            if (null != ApiConfig.getCallFriend()) {
                                ApiConfig.getCallFriend().callbackFriend(response.body());
                            }
                            postValue(response.body());
                        }

                        @Override
                        public void onFailure(@NotNull Call<ApiResponse<T>> call, @NotNull Throwable t) {
                            ApiResponse<T> t1 = new ApiResponse<>(-1, t.getMessage(), null);
                            t1.setOk(false);
                            if (null != ApiConfig.getCallFriend()) {
                                ApiConfig.getCallFriend().callbackFriend(t1);
                            }
                            postValue(t1);
                        }
                    });
                }
            }
        };
        return liveData;
    }
}
